<template>
  <!-- 遮罩层 -->
  <view class="mask" v-show="visible" @click="handleMaskClick">
    <!-- 弹窗内容 -->
    <view class="popup-content" @click.stop>
      <view class="popup-header">
        <text>{{ title }}</text>
      </view>

      <view class="popup-body">
        <scroll-view scroll-y="true" class="description-scroll">
          <text class="desc-text">{{ desc }}</text>
        </scroll-view>

        <!-- 下载进度条 -->
        <view v-if="isDownloading" class="progress-container">
          <progress :percent="progress" :activeColor="progressColor" stroke-width="4"/>
          <text class="progress-text">{{ progress }}%</text>
        </view>
      </view>

      <!-- 按钮组 -->
      <view class="popup-footer" v-if="isShow">
        <button
            v-if="!force"
            class="btn-action cancel-btn"
            @click="close"
            :disabled="isDownloading"
        >以后再说
        </button>
        <my-button
            align="right"
            class="btn-action confirm-btn"
            :class="{'btn-loading': isDownloading}"
            @click="startDownload"
        >
          <text v-if="!isDownloading">立即更新</text>
          <text v-else>下载中...</text>
        </my-button>
      </view>
    </view>
  </view>
</template>

<script>
import config from "../config";
import appUpgrade from "../utils/AppUpgrade";
import MyButton from "../components/functional/button/myButton.vue";
import {setUpdateInfo} from "../utils/auth";

export default {
  components: {MyButton},
  props: {
    isShow: false,
  },
  data() {
    return {
      title: "发现新版本",
      force: false,
      url: '',
      type: "apk",
      desc: "本次更新包含优化和功能改进，建议立即更新",
      visible: false,       // 控制弹窗显示
      progress: 0,         // 下载进度
      isDownloading: false,// 下载状态
      progressColor: "#07c160" // 进度条颜色
    };
  },
  mounted() {
  },
  methods: {
    // 打开弹窗
    show(title, desc, force, url, type) {
      this.visible = true;
      this.title = title
      this.desc = desc
      this.force = force
      this.url = url
      this.type = type
      if (this.force) {
        // 强制更新时拦截返回键
        uni.onBackPress(() => {
          if (this.visible) {
            uni.showToast({
              title: '请完成更新后再使用',
              icon: 'none'
            })
            return true; // 阻止返回
          }
        });
      }
      if (this.url.length > 0 && !this.isShow){
        this.startDownload()
      }
    },

    // 关闭弹窗
    close() {
      if (!this.isDownloading) {
        this.visible = false;
        this.$emit('close');
      } else {
        uni.showToast({
          title: '下载中，无法取消',
          icon: 'none'
        })
      }
    },

    // 遮罩层点击处理
    handleMaskClick() {
      // 非强制更新模式下，点击遮罩层可关闭弹窗
      if (!this.force && !this.isDownloading) {
        this.visible = false;
      }
    },

    // 开始下载
    async startDownload() {
      let that = this
      if (that.isDownloading) return;
      if (that.url.length <= 0) return;
      try {
        that.isDownloading = true;
        that.progress = 0;

        const filePath = await appUpgrade.download(
            config.baseUrl + "/sys/common/static/" + this.url,
            (percent) => {
              console.log(percent)
              that.progress = percent;
              that.progressColor = percent > 70 ? "#07c160" : percent > 30 ? "#ff976a" : "#ff5500";
            }
        );
        await appUpgrade.install(filePath.path, this.type);
        uni.showToast({
          title: '更新完成，应用将重启',
          icon: 'none'
        })
        setUpdateInfo({})
        // 2秒后重启应用
        setTimeout(() => plus.runtime.restart(), 5000);

      } catch (error) {
        console.error('下载失败:', error);
        // uni.showToast({
        //   title: '更新失败: ' + error.message,
        //   icon: 'none'
        // })
        that.isDownloading = false;
      }
    }
  }
};
</script>

<style lang="scss">
// 遮罩层样式
.mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
  transition: opacity 0.3s;
}

// 弹窗内容样式
.popup-content {
  width: 80%;
  max-width: 320px;
  background-color: #fff;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
  animation: popup-enter 0.3s ease-out;

  @keyframes popup-enter {
    from {
      opacity: 0;
      transform: translateY(40px) scale(0.95);
    }
    to {
      opacity: 1;
      transform: translateY(0) scale(1);
    }
  }
}

.popup-header {
  padding: 16px;
  text-align: center;
  background-color: #f5f5f5;
  border-bottom: 1px solid #eee;

  text {
    font-size: 18px;
    font-weight: bold;
    color: #333;
  }
}

.popup-body {
  padding: 16px;
}

.description-scroll {
  max-height: 120px;
  margin-bottom: 15px;

  .desc-text {
    font-size: 14px;
    color: #666;
    line-height: 1.5;
    white-space: pre-line;
  }
}

.progress-container {
  margin-top: 10px;

  progress {
    width: 100%;
  }

  .progress-text {
    display: block;
    text-align: center;
    font-size: 12px;
    color: #999;
    margin-top: 5px;
  }
}

.popup-footer {
  display: flex;
  padding: 12px 16px;
  border-top: 1px solid #eee;

  .btn-action {
    flex: 1;
    height: 36px;
    line-height: 36px;
    margin: 0 5px;
    border-radius: 4px;
    font-size: 14px;
    border: none;

    &::after {
      display: none;
    }

    &:not([disabled]):active {
      opacity: 0.9;
    }

    &[disabled] {
      opacity: 0.6;
    }
  }

  .cancel-btn {
    background-color: #f5f5f5;
    color: #666;
  }
}
</style>
